package com.talent.jiwen;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.SmsResult;
import com.talent.jiwen.my.WebShowActivity;
import com.talent.jiwen.ui.widgets.ClearWriteEditText;
import com.talent.jiwen.util.AMUtils;
import com.talent.jiwen.util.downtime.DownTimer;
import com.talent.jiwen.util.downtime.DownTimerListener;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;

import static com.talent.jiwen.util.Constant.REGISTER_CODE_METHOD;

/**
 * Created by AMing on 16/1/14.
 * Company RongCloud
 */
@SuppressWarnings("deprecation")
public class RegisterActivity extends BaseActivity implements View.OnClickListener, DownTimerListener {


//    private ImageView mImgBackground;
    private String mPhone, mCode, mNickName, mPassword;
    private static final int REGISTER_BACK = 1001;

    @BindView(R.id.reg_phone)
    ClearWriteEditText mPhoneEdit;
    @BindView(R.id.reg_code)
    ClearWriteEditText mCodeEdit;
    @BindView(R.id.reg_username)
    ClearWriteEditText mNickEdit;
    @BindView(R.id.reg_password)
    ClearWriteEditText mPasswordEdit;
//    @BindView(R.id.reg_grade)
//    EditText mGradeEdit;
    @BindView(R.id.cw_invitationcode)
    ClearWriteEditText mInvitationCodeEdit;


    @BindView(R.id.reg_getcode)
    Button mGetCode;
    @BindView(R.id.reg_button)
    Button mConfirm;

    @BindView(R.id.txt_protocol)
    TextView txt_protocol;

    @BindView(R.id.txt_agree)
    TextView txt_agree;


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_register_new;
    }

    @Override
    public String titleName() {
        return "注册";
    }

    @Override
    protected void initData() {
//        StatusBarUtil.setTranslucent(this);
        StatusBarUtil.setColor(this, Color.parseColor("#2F6097"), 100);
//        setHeadVisibility(View.GONE);
        initView();
    }


    private void initView() {
        mGetCode.setOnClickListener(this);
        mGetCode.setClickable(false);
        mConfirm.setOnClickListener(this);
        txt_protocol.setOnClickListener(this);

//        mGradeEdit.setCursorVisible(false);
//        mGradeEdit.setFocusable(false);
//        mGradeEdit.setFocusableInTouchMode(false);
//        mGradeEdit.setOnClickListener(this);

//        TextView goLogin = (TextView) findViewById(R.id.reg_login);
//        TextView goForget = (TextView) findViewById(R.id.reg_forget);
//        goLogin.setOnClickListener(this);
//        goForget.setOnClickListener(this);

//        mImgBackground = (ImageView) findViewById(R.id.rg_img_backgroud);
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Animation animation = AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.translate_anim);
//                mImgBackground.startAnimation(animation);
//            }
//        }, 200);

        addEditTextListener();

    }

    private void addEditTextListener() {
        mPhoneEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11 && isBright) {
                    if (AMUtils.isMobile(s.toString().trim())) {
                        mPhone = s.toString().trim();
                        mGetCode.setClickable(true);
                        mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_blue));
                        AMUtils.onInactive(mContext, mPhoneEdit);//隐藏键盘
                    } else {
                        Toast.makeText(mContext, R.string.Illegal_phone_number, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    mGetCode.setClickable(false);
                    mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_gray));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mCodeEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 4) {
                    AMUtils.onInactive(mContext, mCodeEdit);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mPasswordEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 5) {
                    mConfirm.setClickable(true);
                    mConfirm.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_blue));
                } else {
                    mConfirm.setClickable(false);
                    mConfirm.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_gray));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

//    String[] items = new String[]{"一年级", "二年级", "三年级", "四年级", "五年级", "六年级", "七年级", "八年级", "九年级"};

//    private String mGrade;
//    ChooseGradeDialog gradeDialog;


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.reg_login:
//                startActivity(new Intent(this, LoginActivity.class));
//                break;
//            case R.id.reg_forget:
//                startActivity(new Intent(this, ForgetPasswordActivity.class));
//                break;
            case R.id.reg_getcode:
                if (TextUtils.isEmpty(mPhoneEdit.getText().toString().trim())) {
                    showToast(getString(R.string.phone_number_is_null));
                } else {
                    DownTimer downTimer = new DownTimer();
                    downTimer.setListener(this);
                    downTimer.startDown(60 * 1000);
                    sendCode();
                }
                break;
//            case R.id.reg_grade:
//                gradeDialog=new ChooseGradeDialog(RegisterActivity.this, new ChooseGradeDialog.OnTagClickListener() {
//                    @Override
//                    public void onClick(Dialog dialog, GradeInfo gradeInfo) {
//                        mGrade = String.valueOf(gradeInfo.getGradeId());
//                        mGradeEdit.setText(gradeInfo.getGradeName());
//                    }
//                });
//                gradeDialog.show();
//              gradeDialog.setTagSelect(7);
//                break;
            case R.id.reg_button:
                mPhone = mPhoneEdit.getText().toString().trim();
                mCode = mCodeEdit.getText().toString().trim();
                mNickName = mNickEdit.getText().toString().trim();
                mPassword = mPasswordEdit.getText().toString().trim();


                if (TextUtils.isEmpty(mNickName)) {
                    showToast(getString(R.string.name_is_null));
                    mNickEdit.setShakeAnimation();
                    return;
                }
                if (mNickName.contains(" ")) {
                    showToast(getString(R.string.name_contain_spaces));
                    mNickEdit.setShakeAnimation();
                    return;
                }

                if (TextUtils.isEmpty(mPhone)) {
                    showToast(getString(R.string.phone_number_is_null));
                    mPhoneEdit.setShakeAnimation();
                    return;
                }
                if (TextUtils.isEmpty(mCode)) {
                    showToast(getString(R.string.code_is_null));
                    mCodeEdit.setShakeAnimation();
                    return;
                }
                if (TextUtils.isEmpty(mPassword)) {
                    showToast(getString(R.string.password_is_null));
                    mPasswordEdit.setShakeAnimation();
                    return;
                }
                if (mPassword.contains(" ")) {
                    showToast(getString(R.string.password_cannot_contain_spaces));
                    mPasswordEdit.setShakeAnimation();
                    return;
                }
//                if (Validators.isEmpty(mGrade)) {
//                    showToast(getString(R.string.grade_is_null));
//                    return;
//                }

                if(!isAgree){
                    showToast("请先同意《即问服务协议》");
                    return;
                }
                register();
                break;
            case R.id.txt_protocol:
                WebShowActivity.IS_SERVICE_RIGHT=1;
                WebShowActivity.WEB_SHOW_TYPE=WebShowActivity.WEB_XIE_TYPE;
                Intent intent=new Intent(RegisterActivity.this,WebShowActivity.class);
                startActivityForResult(intent,101);
                break;
        }
    }

    boolean isBright = true;

    @Override
    public void onTick(long millisUntilFinished) {
        mGetCode.setText(String.valueOf(millisUntilFinished / 1000) + "s");
        mGetCode.setClickable(false);
        mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_gray));
        isBright = false;
    }

    @Override
    public void onFinish() {
        mGetCode.setText(R.string.get_code);
        mGetCode.setClickable(true);
        mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_blue));
        isBright = true;
    }

    @Override
    public void onMinTick(String str) {

    }


    private void sendCode() {
        Map<String, String> map = new HashMap<>();
        map.put("method", REGISTER_CODE_METHOD);
        map.put("phone", mPhone);
        Observable observable = ApiFactory.getEducationApiSingleton().sendMsg(map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<SmsResult>(this) {
            @Override
            protected void _onNext(SmsResult smsResult) {
//                if (smsResult != null) {
//                    String code = smsResult.getVcode();
//                    if (Validators.isEmpty(code)) {
//                        showToast(getString(R.string.code_get_fill));
//                    }
//                } else {
//                    showToast(getString(R.string.data_is_wrong));
//                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }


    private void register() {

        String inviteCode = mInvitationCodeEdit.getText().toString().trim();

        Map<String, String> map = new HashMap<>();
        map.put("phone", mPhone);
        map.put("password", mPassword);
        map.put("studentName", mNickName);
        map.put("vCode", mCode);
//        map.put("gradeLevel", mGrade);
        map.put("inviteCode", inviteCode == null ? "" : inviteCode);
        map.put("registerSource", "1");

        Observable observable = ApiFactory.getEducationApiSingleton().studentRegister(map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(this) {
            @Override
            protected void _onNext(Void v) {
                Intent data = new Intent();
                data.putExtra("phone", mPhone);
                data.putExtra("password", mPassword);
                data.putExtra("nickname", mNickName);
                setResult(REGISTER_BACK, data);
                showToast("注册成功");
                finish();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }

//    @Override
//    protected void onStop() {
//        super.onStop();
//        if(gradeDialog!=null && gradeDialog.isShowing()){
//            gradeDialog.dismiss();
//        }
//
//    }

    private boolean isAgree=false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==1001){
            isAgree=true;
            txt_agree.setText("用户已同意");
        }
    }
}
